package com.example.mercury.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.fragment.app.Fragment;

import com.example.mercury.MainActivity;
import com.example.mercury.R;
import com.example.mercury.entity.Register;
import com.example.mercury.entity.User;
import com.example.mercury.utils.HttpUtils;
import com.example.mercury.utils.JsonUtils;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author 盛守义
 * @createTime 2021/10/24 15:43
 * @projectName TurningCoffee
 * @className RegistActivity.java
 * @description TODO
 */
public class RegistActivity extends AppCompatActivity {
    public static Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");

    private View view;
    private Activity activity = RegistActivity.this;

    private EditText et_mail, et_pwd, et_verify, et_username;
    private AppCompatButton btn_verify, btn_submit;
    private Intent intent;
    private String email, pwd, verify, username;

    private String Verification_Code;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        initViews();
        setListener();
    }


    void initViews(){
        et_mail = findViewById(R.id.et_emailrgt);
        et_pwd = findViewById(R.id.et_pwdrgt);
        et_verify = findViewById(R.id.et_verifyrgt);
        et_username = findViewById(R.id.et_username);
        btn_verify = findViewById(R.id.btn_verifyrgt);
        btn_submit = findViewById(R.id.btn_submitrgt);
    }

    void initValue(){
        email = et_mail.getText().toString().trim();
        pwd = et_pwd.getText().toString().trim();
        username = et_username.getText().toString().trim();
        verify = et_verify.getText().toString().trim();
    }

    void setListener(){
        subClickListener listener = new subClickListener();
        btn_verify.setOnClickListener(listener);
        btn_submit.setOnClickListener(listener);
    }

    class subClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.btn_verifyrgt:
                    if(et_mail.getText().toString().trim() == null || et_mail.getText().toString().trim().equals("")){
                        Toast.makeText(activity, "输入不能为空", Toast.LENGTH_SHORT).show();
                    }
                    else if(isEmail(et_mail.getText().toString().trim()) && et_mail.getText().toString().trim().length()<=31){
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("emailAddress", et_mail.getText().toString().trim());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        String jsonString = jsonObject.toString();

                        HttpUtils httpUtils = new HttpUtils();
                        FormBody.Builder requestBuild = new FormBody.Builder();
                        RequestBody requestBody = requestBuild.add("emailAddress", et_mail.getText().toString().trim()).build();

                        //url
                        Call call = httpUtils.getPostCall(requestBody, "http://10.7.88.9:8004","/email");
                        call.enqueue(new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(activity, "网络连接崩溃了，绝对绝对不是我们的错", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }

                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                String res = response.body().string();
                                Log.e("regist验证码", res);
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Verification_Code = res;
                                        if(Verification_Code.equals("邮件发送失败")){
                                            Toast.makeText(activity, Verification_Code, Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                            }
                        });
                    }
                    else{
                        Toast.makeText(activity, "邮箱格式错误", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.btn_submitrgt:
                    initValue();

                    if (email == null || email.equals("") || pwd == null || pwd.equals("") || verify == null || verify.equals("")||username == null || username.equals("")) {
                        Toast.makeText(activity, "输入不能为空", Toast.LENGTH_SHORT).show();
                    }
                    else if(verify == Verification_Code.trim() || verify.equals(Verification_Code.trim())){
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("userTel", email);
                            jsonObject.put("userPassword", pwd);
                            jsonObject.put("userNickname", username);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        String jsonString = jsonObject.toString();
                        Log.e("jsonString:", jsonString);
                        //发送用户名密码并接收
                        HttpUtils httpUtils = new HttpUtils();
                        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonString);

                        //输入url
                        Call call = httpUtils.getCall(requestBody,"/user/register");
                        call.enqueue(new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                RegistActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(activity, "网络连接崩溃了，绝对绝对不是我们的错", Toast.LENGTH_SHORT).show();
                                    }
                                });

                            }

                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                String res = response.body().string();
                                Log.e("返回信息", res);
                                User user = new JsonUtils().getUser(res);
                                RegistActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (user.getSuccess() == true) {
                                            Intent intent = new Intent(RegistActivity.this, LoginActivity.class);
                                            startActivity(intent);
                                            RegistActivity.this.finish();
                                        }
                                    }
                                });

                            }
                        });
                    }
                    else {
                        Log.e("Verification_Code", Verification_Code);
                        Log.e("verify", verify );
                        Toast.makeText(activity, "验证码错误", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    }

    public static boolean isEmail(String email){
        if (null==email || "".equals(email)) return false;
        Matcher m = p.matcher(email);
        return m.matches();
    }
}